#encoding: utf-8
#pip install PIL --allow-external PIL --allow-unverified PIL
#OR
#apt-get install python-imaging libjpeg-dev libfreetype6-dev zlib1g-dev libpng12-dev
from PIL import Image, ImageDraw, ImageFont, ImageFilter
import string, random,sys
from random import  sample
'''
jk409@qq.com created by 2016-7-8
功能：验证码改良版
'''

# 获得随机四个数组或字母
class Codes:
    def __init__(self,img_path,img_name,img_type='png'):
        self.img_path=img_path
        self.img_name=img_name
        self.img_type=img_type

    def get_code(self):
        code_list = ['z', 'y', 'x', 'w', 'v', 'u', 't', 's', 'r', 'q', 'p', 'o', 'n', 'm', 'l', 'k', 'j', 'i', 'h', 'g',
                     'f', 'e', 'd', 'c', 'b', 'a',
                     '1', '2', '3', '4', '5', '6', '7', '8', '9',
                     'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
                     'U', 'V', 'W', 'X', 'Y', 'Z'
                     ]
        leng = 4  # 定义长度
        data = "".join(sample(code_list, leng)).replace(' ', '')
        return list(data)

    # 获得随机四个字母
    def getRandomChar(self):
        data = [random.choice(string.letters) for _ in range(4)]
        return data

    # 获得颜色
    def getRandomColor(self):
        return (random.randint(30, 100), random.randint(30, 100), random.randint(30, 100))

    # 获得验证码图片
    def getCodePiture(self):
        width = 240
        height = 60
        # 创建画布
        # image = Image.new('RGB', (width, height), (180,180,180))
        image = Image.new('RGB', (width, height), (26, 179, 148))
        font = ImageFont.truetype('./GADUGI.TTF', 40)
        draw = ImageDraw.Draw(image)
        # 创建验证码对象
        # code = getRandomChar()
        code = self.get_code()
        # 把验证码放到画布上
        for t in range(4):
            draw.text((60 * t + 10, 0), code[t], font=font, fill=self.getRandomColor())
        # 填充噪点
        #for _ in range(random.randint(1500, 3000)):
        #    draw.point((random.randint(0, width), random.randint(0, height)), fill=self.getRandomColor())
        # 模糊处理
        image = image.filter(ImageFilter.BLUR)
        # 保存名字为验证码的图片
        image.save("".join(self.img_path + self.img_name) + '.%s'%self.img_type, 'jpeg')

if __name__ == '__main__':
    codes=Codes('./','code')
    codes.getCodePiture()